const router = require('koa-router')();
const users = require('../models/users');

const crypto = require('crypto');

// 密码哈希验证函数
const validatePassword = (inputPassword, storedHash) => {
  const inputHash = crypto.createHash('sha256').update(inputPassword).digest('hex');
  return inputHash === storedHash;
};


const { generateToken } = require('../authUtil');

router.prefix('/api/users');

router.post('/register', function* (next) {
  const { login_name, password } = this.request.body;
  if (!login_name || !password) {
    this.body = { status: 1, msg: 'Username and password are required' };
    return;
  }
  const result = users.createUser(login_name, password);
  this.body = result;
});

router.post('/login', function* (next) {
  const { login_name, password } = this.request.body;
  const user = users.findUserByUsername(login_name);
  if (!user) {
    this.body = { status: 1, msg: 'Authentication failed. User not found.' };
    return;
  }
  // 使用 validatePassword 函数来验证密码
  const passwordIsValid = validatePassword(password, user.password);
  
  if (!passwordIsValid) {
    this.body = { status: 1, msg: 'Authentication failed. Wrong password.' };
    return;
  }
  // 生成 JWT
  const token = generateToken({ userId: user.id });
  this.body = { status: 0, msg: 'Login successful', userId: user.id, token };
});

module.exports = router;

